'use strict';

require(['angular', './lib/promisify/promisify', 'angular-ui-router', './mstore/home/home', 'angular-growl', 'angular-material', 'theme-palette', 'angular-locale_zh-cn', './common/mpj/filters'], function (angular) {
	var module = angular.module('mstoreApp', ['ui.router', 'mstoreHome', 'angular-growl', 'ngMaterial', 'mpjGlobalFilter', 'mpj.material.core.theming.palette', 'material.core']);
	module.config(['$stateProvider', 'growlProvider', function ($stateProvider, growlProvider) {
		$stateProvider.state('index', {
			url: '',
			controller: 'IndexCtrl'
		});
	}]);

	module.config(['$mdColorPalette', '$mdThemingProvider', function ($mdColorPalette, $mdThemingProvider) {
		angular.forEach($mdColorPalette, function (palette, themeId) {
			$mdThemingProvider.definePalette(themeId, palette);
			$mdThemingProvider.theme(themeId).primaryPalette(themeId);
		});
		$mdThemingProvider.alwaysWatchTheme(true);
	}]);

	module.controller('IndexCtrl', ['$state', '$location', '$rootScope', 'dataService', function ($state, $location, $rootScope, dataService) {
		$rootScope.themeId = 'lovely-yellow';
		dataService.getStoreInfo(sessionStorage.store, function (err, dataObj) {
			if (err) {
				$rootScope.showMessage(dataObj.error);
				return;
			}
			$rootScope.themeId = 'lovely-yellow';
			//$mdTheming.setDefaultTheme(dataObj.settings.theme_id);
			sessionStorage.store = dataObj.store.id || dataObj.store.ID;
			sessionStorage.storeInfo = JSON.stringify(dataObj);
			$rootScope.storeLoaded = true;
			$state.transitionTo('home');
		});

	}]);
	module.factory('appService', ['$rootScope', function ($rootScope) {
		return {
			// memberBound:function(cb) {
			//     if (sessionStorage.memberid) {
			//         cb(null);
			//     }
			//         $rootScope.$on('member.bound', cb);
			// }
		}
	}]);
	module.run(['$rootScope', '$location', 'dataService', '$mdToast', '$state', '$mdTheming', function ($rootScope, $location, dataService, $mdToast, $state, $mdTheming) {
		$rootScope.$watch('pageTitle', function (newTitle) {
			document.getElementById('iframe').innerHTML = ('<iframe src="/images/logo.jpg"></iframe>');
		})
		$rootScope.memberBound = function (cb, options) {
			if (sessionStorage.memberId) {
				return cb(null);
			}
			this.$on('member.bound', cb);
			if ((options || {}).force) {
				$rootScope.$on('member.not.bound', function () {
					if (!sessionStorage.memberId || sessionStorage.memberId == 'undefined') {
						sessionStorage.loginBackState = $state.current.name;
						$state.transitionTo("login");
					}
				});
				if (memberRetrieved) {
					if (sessionStorage.memberId)
						$rootScope.$broadcast('member.bound');
					else
						$rootScope.$broadcast('member.not.bound');
				}
			}
		};
		$rootScope.bindMember = function (memberId) {
			sessionStorage.memberId = memberId;
			$rootScope.memberId = memberId;
			$rootScope.$broadcast('member.bound');
		}

		function getQueryString(name)
		{
			var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
			var r = window.location.search.substr(1).match(reg);
			if(r!=null)return  unescape(r[2]); return null;
		}
		sessionStorage.store = location.pathname.split('/')[2];
		sessionStorage.code = getQueryString('code');
		sessionStorage.sns = $location.search().sns;

		if ('undefined' == sessionStorage.sns) {
			sessionStorage.sns = "mstore";
		}
		dataService.getStoreInfo(sessionStorage.store, function (err, dataObj) {
			if (err) {
				$rootScope.showMessage(dataObj.error);
				return;
			}
			$rootScope.themeId = 'lovely-yellow';
			//$rootScope.themeId = dataObj.settings.theme_id;
			//$mdTheming.setDefaultTheme(dataObj.settings.theme_id);
			sessionStorage.store = dataObj.store.id || dataObj.store.ID;
			sessionStorage.storeInfo = JSON.stringify(dataObj);
			$rootScope.storeLoaded = true;
		});
		var memberRetrieved = false;

		function handleMember() {
			if (!sessionStorage.memberId || sessionStorage.memberId == 'undefined') {
				/**
				 * 获取绑定
				 */
				dataService.getMemberBind(sessionStorage.store, sessionStorage.openId, sessionStorage.sns, function (err, member) {
					memberRetrieved = true;
					if (err) {
						if (err.code == 'not-bound')
							return $rootScope.$broadcast('member.not.bound');
						return;
					}
					if (!member) return;
					$rootScope.bindMember(member.id);
				})
			} else {
				$rootScope.memberId = sessionStorage.memberId;
				memberRetrieved = true;
			}
		}

		$rootScope.handleMember = handleMember;

		setTimeout(function () {
			if (sessionStorage.code) {
				dataService.getOpenId(sessionStorage.store, sessionStorage.code, sessionStorage.sns, function (err, ret) {
					if (err) return;
					sessionStorage.openId = ret.openid;
					delete sessionStorage.code;
					handleMember();
				});
			} else {
				handleMember();
			}
		});

		$rootScope.goBack = function () {
			window.history.back();
		}
		$rootScope.showMessage = function (msg) {
			$rootScope.msg = msg;

			$mdToast.show({
				templateUrl: '/page/show.html',
				hideDelay: 3000,
				position: "top left"
			});
		}
		$rootScope.closeToast = function () {
			$mdToast.cancel('fff');
		};

		// 判断是否为PC端
		function IsPC() {
			var userAgentInfo = navigator.userAgent;
			var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod");
			var flag = true;
			for (var v = 0; v < Agents.length; v++) {
				if (userAgentInfo.indexOf(Agents[v]) > 0) {
					flag = false;
					break;
				}
			}
			return flag;
		}

		// PC端加上右边导航按钮

		var conWid = 540;
		var bodyWid = document.body.clientWidth;
		if (IsPC()) {
			document.getElementById('operationBtn').style.right = (bodyWid - conWid) / 2 - 50 + 'px';
		} else {
			var obj = document.getElementById('operationBtn');
			obj.parentNode.removeChild(obj);
		}

	}]);

	var $html = angular.element(document);
	$html.ready(function () {
		angular.bootstrap($html, ['mstoreApp']);
		$html.addClass('ng-app');

	});
});
